package org.gruposp2p.openid

import org.openid4java.message.Message;
import org.gruposp2p.openid.util.OpenIdProviderService;
import groovy.xml.MarkupBuilder
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
import grails.converters.*;
import org.openid4java.message.ParameterList;
import org.gruposp2p.openid.util.RegistrationModel;
import org.openid4java.message.DirectError;
import org.gruposp2p.openid.provider.UserDNI;
import grails.plugins.springsecurity.Secured
import org.gruposp2p.openid.provider.OpenIdUser;

class EndpointURLController {
	
	def springSecurityService
	
	def beforeInterceptor = [action:this.&debug]

 	def debug(){
		log.debug "##########################################################################"
		log.debug "request.getRemoteAddr(): " + request.getRemoteAddr()
		log.debug "request.getHeader(X-Forwarded-For): " + request.getHeader("X-Forwarded-For")
		log.debug "request.getHeader(Client-IP): " + request.getHeader("Client-IP")
		log.debug "request.forwardURI: " + request.forwardURI
		log.debug "params: " + params
		log.debug "##########################################################################"
 	}
	
	def index = {
		Message responseMessage;
		ParameterList requestParameters = 
			new ParameterList(request.getParameterMap());
		session.requestParameters = requestParameters;
		if (requestParameters.hasParameter("openid.mode")) {
			OpenIdProviderService.logRequestParameters(
					requestParameters);
			String mode = requestParameters.getParameterValue("openid.mode")
			if ("associate".equals(mode)) {
				log.debug "Processing OpenID request mode: '" + mode + "'..."
				OpenIdProviderService.processAssociationRequest(response, requestParameters);
		    } else if ("checkid_immediate".equals(mode) ||
		    		   "checkid_setup".equals(mode) || "check_authentication".equals(mode)) {
		    		session.openIDIdentity = requestParameters.getParameterValue("openid.identity")
		    		log.debug "Processing OpenID request mode: '" + mode + "'..." + " - openid.identity: " + requestParameters.getParameterValue("openid.identity") 
		    		if (!springSecurityService.isLoggedIn()) {
		    			render view: 'accesoDNIe'
						return
					}
					//redirect(action:checkId, params:params)
		    		chain(action:checkId, params:params)
		      } 
		    /*
		    else if ("check_authentication".equals(mode)) {
		    	  log.debug "Processing OpenID request mode: '" + mode + "'..."
		    	  responseMessage = OpenIdProviderService.verifyCheckAuthentication(requestParameters);
		    	  log.debug "responseMessage: '" + responseMessage + "'"
		          String responseText = responseMessage.keyValueFormEncoding();
		          render responseText;
		      }*/ else {
		        log.debug("Unknown request mode '" + mode);
		      }			
		} else {
			log.debug("-- Unknown request --");
			responseMessage =DirectError.createDirectError("Unknown request");
            String responseText = responseMessage.keyValueFormEncoding();
            render responseText;
		}		
	}
	
	@Secured(['ROLE_USER'])
	def checkId = {
		OpenIdUser userDetails = springSecurityService.principal
        log.debug("---- userDetails: " + userDetails);
        def user = UserDNI.get(userDetails.getId())			          
        sendSuccessfulResponse(session.requestParameters, user);
	}

	@Secured(['ROLE_USER'])
	def sendResponse = { requestParameters, user ->
		log.debug "---- sendResponse() BEGIN... - requestParameters: " + requestParameters + " - user: " + user
		RegistrationModel registrationModel = new RegistrationModel ();	
		registrationModel.setEmailAddress user.getEmail()
		registrationModel.setFullName user.getUsername()
		registrationModel.setTransaction 'ok'
		Message authResponse = OpenIdProviderService.buildAuthResponse(
		    requestParameters, user.getUserOpenID(), user.getUserOpenID(),
		    registrationModel);
		redirect(url:authResponse.getDestinationUrl(true));
		log.debug "---- sendResponse() END..."
	}
	
	 private void sendSuccessfulResponse(ParameterList requestParameters, UserDNI user) {
		log.debug "---- sendSuccessfulResponse BEGIN... - requestParameters: " + requestParameters + " - user: " + user
		RegistrationModel registrationModel = new RegistrationModel ();	
		registrationModel.setEmailAddress user.getEmail()
		registrationModel.setFullName user.getUsername()
		registrationModel.setTransaction 'ok'
	    Message authResponse = OpenIdProviderService.buildAuthResponse(
	        requestParameters, user.getUserOpenID(), user.getUserOpenID(),
	        registrationModel);
	    redirect(url:authResponse.getDestinationUrl(true));
		log.debug "---- sendSuccessfulResponse END..."
	  }
	
}